package com.leetcode.partition2;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/8/2 10:56
 */
public class LC107二叉树的层序遍历2 {

    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        return dfs(root);
    }

    public static void main(String[] args) {

    }

    //dfs：通过LC102题得到正常序列后，对其反转
    private static List<List<Integer>> dfs(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(result, root, 0);
        Collections.reverse(result);
        return result;
    }

    private static void dfs(List<List<Integer>> result, TreeNode root, int level) {
        if (root == null) return;
        if (level > result.size() - 1) result.add(new ArrayList<>());
        result.get(level).add(root.val);
        if (root.left != null) dfs(result, root.left, level + 1);
        if (root.right != null) dfs(result, root.right, level + 1);
    }

    //bfs
    private static List<List<Integer>> bfs(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if (root == null) return result;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> item = new ArrayList<>();
            while (size > 0) {
                TreeNode current = queue.poll();
                item.add(current.val);
                if (current.left != null) queue.add(current.left);
                if (current.right != null) queue.add(current.right);
                size--;
            }
            result.addFirst(item);
        }
        return result;
    }
}
